﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MathematicallySafe.HeadCounter.Data;
using MathematicallySafe.HeadCounter.Data.Common;

namespace MathematicallySafe.HeadCounter.Services.Backup
{
    internal class ArchiveManager
    {
        public string ArchiveLocation { get; set; }

        public ArchiveManager()
        {
            if (!Directory.Exists(Constants.BackupDirectory)) Directory.CreateDirectory(Constants.BackupDirectory);
        }

        public string GenerateName()
        {
            var newArchiveName = string.Format("hcr-{0:yyyy-MM-dd_hh-mm-ss-tt}.zip", DateTime.Now);
            return newArchiveName;
        }

        public void TrimArchive(int depth)
        {
            if (depth == 0) return;
            var archives = GetExistingArchives();

            int n = archives.Count - depth;

            if (n > 0)
            {
                var archivesForDeletion = archives.Take(n);
                archivesForDeletion.ForEach(a => File.Delete(a.Value));
            }
        }

        private IDictionary<DateTime, string> GetExistingArchives()
        {
            var archives = new SortedDictionary<DateTime, string>();

            var directoryInfo = new DirectoryInfo(ArchiveLocation);
            var archiveFiles = directoryInfo.GetFiles("*.zip");

            foreach(var fileInfo in archiveFiles)
            {
                archives.Add(fileInfo.CreationTimeUtc, fileInfo.FullName);    
            }

            return archives;
        }
    }
}


